<script setup lang="ts">
import { useI18n } from '@/hooks/web/useI18n'
// import { useIcon } from '@/hooks/web/useIcon'
import { reactive, watch, ref } from 'vue'
import {
  getDeliverByWaybill,
  customsSelect,
  emp_foreignSelect,
  deliverGetSelectList
} from '@/api/common'

import {
  ElForm,
  ElFormItem,
  ElButton,
  ElInput,
  ElRow,
  ElCol,
  ElTable,
  ElTableColumn,
  ElSelect,
  ElOption,
  ElDatePicker,
  ElMessage,
  ElUpload,
  ElMessageBox
} from 'element-plus'

import type { UploadProps, UploadUserFile } from 'element-plus'

import * as xlsx from 'xlsx'
import { useCache } from '@/hooks/web/useCache'
import { table } from 'console'
import { sum } from 'lodash-es'

const { wsCache } = useCache()
const getToken = wsCache.get('userInfo') ? wsCache.get('userInfo').token : ''
const fileList = ref<UploadUserFile[]>([])

/**
 * 把文件按照二进制进行读取
 * @param file
 * @returns
 */
const readFile = (file: File) => {
  return new Promise((resolve) => {
    let reader = new FileReader()
    reader.readAsBinaryString(file)
    reader.onload = (ev) => {
      resolve(ev.target?.result)
    }
    console.log(reader)
  })
}

/**
 * 根据sheet索引读取Excel文件中的数据
 /**@param file 文件
 /** @param sheetIndex excel文件中sheet表索引 默认是从0开始
 /**@returns  将表中的数据以json形式的数据返回
*/
const readExcelFile = async (file: File, sheetIndex: number) => {
  let data: any = await readFile(file)
  let workbook = xlsx.read(data, { type: 'binary' })
  let worksheet = workbook.Sheets[workbook.SheetNames[sheetIndex]]
  data = xlsx.utils.sheet_to_json(worksheet)
  console.log(data)
  let key = {
    运单号: 'waybill',
    清关价格: 'customs_price',
    转出货值: 'export_value',
    保率: 'export_insurance_rate'
  }

  if (data && data.length > 0) {
    let i = 0
    for await (let item of data) {
      let obj: any = {}
      for (let name in item) {
        obj[key[name]] = item[name]
      }
      tableData.push(obj)
      console.log('---数据索引值---', tableData.length - 1)
      await getDeliverByWaybillFn(obj.waybill, tableData.length - 1)
      Object.assign(tableData[tableData.length - 1], obj)
      i++
    }
    if (i == data.length) {
      sumFn()
    }
  }
  // return data
}
const before = (file: any) => {
  readExcelFile(file, 0)
  return false
}

// 计算重量合计 体积合计 密度合计
const sumFn = () => {
  form.weight = 0
  form.export_weight = 0
  form.volume = 0
  form.export_volume = 0
  form.avg_density = 0
  form.export_avg_density = 0

  tableData.forEach((item) => {
    if (item.export_weight) {
      form.weight += Number(item.export_weight)
      form.export_weight += Number(item.export_weight)
    }
    if (item.export_volume) {
      form.volume += Number(item.export_volume)
      form.export_volume += Number(item.export_volume)
    }
    if (item.export_density) {
      form.avg_density += Number(item.export_density)
      form.export_avg_density += Number(item.export_density)
    }
    if (item.customs_money) {
      form.total_fee += Number(item.customs_money)
    }
  })
}

const sumMoney = () => {
  form.total_fee = 0
  tableData.forEach((item) => {
    if (item.customs_money) {
      form.total_fee += Number(item.customs_money)
    }
  })
}

// 运费计算方式
const freightCalculationMethodArr: any = reactive([])

const getOptions = async () => {
  let res: any = await deliverGetSelectList()
  //运费计算
  for (let a in res.data.transportTypeList) {
    let b = res.data.transportTypeList[a]
    freightCalculationMethodArr.push({
      label: b,
      value: a
    })
  }
  console.log(freightCalculationMethodArr, '下拉列表集合')
}

getOptions()

const { t } = useI18n()

// const addIcon = useIcon({ icon: 'gala:add' })
// const delIcon = useIcon({ icon: 'material-symbols:delete-outline' })

const props = defineProps({
  currentRow: {
    type: Object as any,
    default: () => null
  }
})

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    // form.id = currentRow.id
  }
)

// 表单对应的字段（绑定到输入框以及选择框俄字段）
const form: any = reactive({
  batchno: '', //批号
  customs_id: '', //清关公司
  quantity: '', //数量合计
  volume: '', //体积合计
  density: '', //密度合计
  weight: '', //重量合计
  units: '', //件数合计
  export_weight: '', // 转出重量
  export_volume: '', //转出体积
  export_density: '', //转出密度
  total_fee: '', //清关金额合计
  price: '', //清关价格合计
  mobile: '', //莫办电话
  worker: '', //莫办人员
  margin: '', //毛利润合计
  internal_charge: '', //国内费用合计
  pledge: '', //押金合计
  foreign_charge: '', //国外费用合计
  createtime: '', //
  updatetime: '', //修改时间10位时间戳
  customs_date: '', //清关日期
  status: '', //单据状态
  audit_user: '', //审核人
  audit_time: '', //审核时间
  update_user: '', //修改人
  total_vote: '', //总票数
  avg_density: '', //平均密度
  export_avg_density: '', //转出平均密度
  exterior_user: '', //外办人员
  exterior_mobile: '', //外办电话
  remark: '', //备注
  export_transport: '', //转出运输方式
  deliverList: [] // 出货单的数据
})

// 清关公司下拉选择
const customArr: any = reactive([])
const getCustomArr = async () => {
  let res = await customsSelect()
  console.log('---清关公司数据---', res)
  res.data.list.forEach((item) => {
    customArr.push({
      label: item.name,
      value: item.id,
      transport: item.transport
    })
  })
}
getCustomArr()

const getDeliverByWaybillFn = async (waybill, index) => {
  console.log('---运单号---', waybill, index)
  let res = await getDeliverByWaybill({
    waybill: waybill
  })
  if (res && res.code == '1' && res.data[0]) {
    //如果查到订单
    console.log('---根据运单号获取出库单---', res.data[0])
    let data = res.data[0]
    data.export_weight = data.weight
    data.export_volume = data.volume
    data.export_value = data.usd_value
    data.export_density = data.density.toFixed(2)
    data.valuePreservationPerKilogram = (data.usd_value / data.export_weight).toFixed(2)
    tableData[index] = res.data.length >= 0 ? data : []
  }
}

let selectArr: any = []
// 删除选中的数据
const delSelectFn = () => {
  ElMessageBox.confirm('是否删除选中数据', '提示', {
    confirmButtonText: t('common.delOk'),
    cancelButtonText: t('common.delCancel'),
    type: 'warning'
  }).then(() => {
    const noDelArr = tableData.filter((item) => {
      return !selectArr.includes(item.id)
    })
    console.log('----不删除的数据----', noDelArr)
    // tableData.value = noDelArr
    tableData.length = 0
    noDelArr.forEach((item) => {
      tableData.push(item)
    })
    ElMessage.success('提交成功')
  })
}

// 选择某条数据
const selectionChange = (ev) => {
  console.log('---选择改变ev---', ev)
  selectArr = []
  ev.forEach((item: any) => {
    selectArr.push(item.id)
  })
}

// 增加出库单
const addFhdFn = () => {
  tableData.push({
    waybill: ''
  })
}

// 监听运单号
let timer: any = null
const changeWaybill = async (ev, index) => {
  console.log('---监听---', ev, index)
  let data = tableData.find((item, index) => {
    return item.waybill == ev
  })
  if (data.id) {
    ElMessage({
      message: '订单号重复，请勿重复提取数据',
      type: 'warning'
    })
    return false
  }
  await getDeliverByWaybillFn(ev, index)
  sumFn()
}

defineExpose({
  getFormData: () => {
    return form
  },
  getTableData: () => {
    return tableData
  }
})
//获取外办人员
const foreignArr: any = reactive([])
const getforeignArr = async () => {
  let res = await emp_foreignSelect()
  // console.log(res)
  res.data.list.forEach((item) => {
    foreignArr.push({
      label: item.name,
      value: item.name,
      mobile: item.mobile
    })
  })
}
//获取外办人员手机号
const getPhone = (name) => {
  // console.log(name)
  let data = foreignArr.find((item) => {
    return item.value == name
  })
  form.exterior_mobile = data.mobile
}
getforeignArr()
//获取转出运输方式
const transportArr: any = reactive([])
const getExportTranspor = (e) => {
  // console.log(e)
  transportArr.length = 0
  let data = customArr.find((item) => {
    return item.value == e
  })
  let arr = data.transport ? JSON.parse(data.transport) : []
  if (arr.length > 0) {
    arr.forEach((element) => {
      transportArr.push(element)
    })
  }
  console.log('----transportArr-----', transportArr)
}
//选择区间
const select_export_transpor = (ev, index) => {
  // console.log('---选择运输方式---', ev, index)
  let way: any = transportArr.find((item) => {
    return item.name == ev
  })

  let price: any = 0
  console.log('---选择运输方式计算价格---', tableData[index].transport_type)
  let jsType = tableData[index].transport_type
  if (jsType == 1 && tableData[index].export_weight) {
    let indexZl = Number(tableData[index].export_weight)
    way.Zlist.forEach((item) => {
      if (Number(item.min) <= indexZl && indexZl <= Number(item.max)) {
        price = Number(item.name)
      }
    })

    tableData[index].customs_money = price * indexZl
    console.log('---选择运输方式计算价格-计算结果--', tableData[index].customs_money)
    sumMoney()
  }
  if (jsType == 2 && tableData[index].export_volume) {
    let indexTj = Number(tableData[index].export_volume)
    way.Tlist.forEach((item) => {
      if (Number(item.min) <= indexTj && indexTj <= Number(item.max)) {
        price = Number(item.name)
      }
    })

    tableData[index].customs_money = price * indexTj
    console.log('---选择运输方式计算价格-计算结果--', tableData[index].customs_money)
    sumMoney()
  }
}
let tableData: any = reactive([])

// 运费计算方式更改
const yunfeiChange = (ev, index) => {
  console.log('---运费计算变更---', ev, index, tableData[index].export_transpor)
  let way: any = transportArr.find((item) => {
    return item.name == tableData[index].export_transpor
  })
  let price: any = 0
  console.log('---选择运输方式计算价格---', ev, way)
  if (ev == 1 && tableData[index].export_weight) {
    let indexZl = Number(tableData[index].export_weight)
    way.Zlist.forEach((item) => {
      if (Number(item.min) <= indexZl && indexZl <= Number(item.max)) {
        price = Number(item.name)
      }
    })

    tableData[index].customs_money = price * indexZl
    console.log('---选择运输方式计算价格-计算结果--', tableData[index].customs_money)
    sumMoney()
  }
  if (ev == 2 && tableData[index].export_volume) {
    let indexTj = Number(tableData[index].export_volume)
    way.Tlist.forEach((item) => {
      if (Number(item.min) <= indexTj && indexTj <= Number(item.max)) {
        price = Number(item.name)
      }
    })

    tableData[index].customs_money = price * indexTj
    console.log('---选择运输方式计算价格-计算结果--', tableData[index].customs_money)
    sumMoney()
  }

  if (ev == 3 || ev == 99) {
    ElMessage.info('请手动输入清关金额')
  }
}
</script>

<template>
  <ElForm :model="form" label-width="auto">
    <ElRow>
      <ElCol :span="6">
        <ElFormItem label-width="150px" :label="t('customsClearanceForm.batchNumber')">
          <ElInput v-model="form.batchno" />
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="150px" :label="t('invoice.totalNumberOfpices')">
          <ElInput v-model="form.units" disabled />
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="150px" :label="t('invoice.documentStatus')">
          <ElInput v-model="form.status" />
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="150px" label="制单人">
          <ElInput v-model="form.enact" disabled />
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="150px" :label="t('router.CustomsClearanceFormCompany')">
          <ElSelect
            v-model="form.customs_id"
            @change="getExportTranspor"
            :placeholder="t('common.selectText')"
            filterable
          >
            <ElOption
              v-for="item in customArr"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="150px" label="重量合计">
          <ElInput v-model="form.weight" disabled />
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="150px" :label="t('customsClearanceForm.transferOutWeight')">
          <ElInput v-model="form.export_weight" />
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="150px" label="制单时间">
          <ElDatePicker
            v-model="form.xxx"
            type="date"
            disabled
            value-format="YYYY-MM-DD"
            :placeholder="t('common.selectText')"
            :shortcuts="[
              {
                text: '今天',
                value: new Date()
              }
            ]"
          />
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="150px" label="总票数">
          <ElInput v-model="form.total_vote" disabled />
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="150px" :label="t('customsClearanceForm.totalVolume')">
          <ElInput v-model="form.volume" disabled />
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="150px" :label="t('customsClearanceForm.transferOutVolume')">
          <ElInput v-model="form.export_volume" />
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="150px" label="审核人">
          <ElInput v-model="form.audit_user" disabled />
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="150px" label="外办人员">
          <ElSelect
            v-model="form.exterior_user"
            :placeholder="t('common.selectText')"
            filterable
            @change="getPhone"
          >
            <ElOption
              v-for="item in foreignArr"
              :key="item.id"
              :label="item.label"
              :value="item.value"
              filterable
            />
          </ElSelect>
        </ElFormItem>
      </ElCol>

      <ElCol :span="6">
        <ElFormItem label-width="150px" label="平均密度">
          <ElInput v-model="form.avg_density" disabled />
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="150px" label="转出平均密度">
          <ElInput v-model="form.export_avg_density" />
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="150px" label="审核时间">
          <ElDatePicker
            v-model="form.audit_time"
            type="date"
            disabled
            value-format="YYYY-MM-DD"
            :placeholder="t('common.selectText')"
            :shortcuts="[
              {
                text: '今天',
                value: new Date()
              }
            ]"
          />
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="150px" label="外办电话">
          <ElInput v-model="form.exterior_mobile" disabled />
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="150px" label="清关日期">
          <ElDatePicker
            v-model="form.customs_date"
            type="date"
            value-format="YYYY-MM-DD"
            :placeholder="t('common.selectText')"
            :shortcuts="[
              {
                text: '今天',
                value: new Date()
              }
            ]"
          />
        </ElFormItem>
      </ElCol>
      <ElCol :span="6" />
      <ElCol :span="6">
        <ElFormItem label-width="150px" label="修改人">
          <ElInput v-model="form.update_user" disabled />
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="150px" label="总应收费用合计">
          <ElInput v-model="form.total_money" />
        </ElFormItem>
      </ElCol>

      <ElCol :span="6">
        <ElFormItem label-width="150px" label="清关合计金额">
          <ElInput v-model="form.total_fee" />
        </ElFormItem>
      </ElCol>

      <ElCol :span="6">
        <ElFormItem label-width="150px" :label="t('customsClearanceForm.totalGrossProfit')">
          <ElInput v-model="form.margin" />
        </ElFormItem>
      </ElCol>

      <ElCol :span="6">
        <ElFormItem label-width="150px" label="修改日期">
          <ElDatePicker
            v-model="form.update_date"
            type="date"
            disabled
            value-format="YYYY-MM-DD"
            :placeholder="t('common.selectText')"
            :shortcuts="[
              {
                text: '今天',
                value: new Date()
              }
            ]"
          />
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="150px" label="备注">
          <ElInput v-model="form.remark" />
        </ElFormItem>
      </ElCol>
    </ElRow>
  </ElForm>
  <ElRow>
    <ElCol :span="24">
      <!-- <ElButton>导入</ElButton> -->
      <ElUpload
        class="upload_file"
        v-model:file-list="fileList"
        :limit="1"
        accept="xlsx, xls"
        :headers="{
          token: getToken
        }"
        :before-upload="before"
      >
        <ElButton type="primary">导入</ElButton>
      </ElUpload>
      <ElButton @click="addFhdFn">新增</ElButton>
      <ElButton @click="delSelectFn">删除</ElButton>
    </ElCol>
  </ElRow>
  <ElRow>
    <ElCol :span="24">
      <ElTable
        :data="tableData"
        style="width: 100%"
        ref="multipleTable"
        @selection-change="selectionChange"
      >
        <ElTableColumn type="selection" width="55" />
        <ElTableColumn prop="waybill" label="运单号" width="200">
          <template #default="scope">
            <ElInput
              v-model="scope.row.waybill"
              :placeholder="t('common.inputText')"
              @blur="changeWaybill(scope.row.waybill, scope.$index)"
            />
          </template>
        </ElTableColumn>
        <ElTableColumn prop="export_transport" width="200" label="转出运输方式">
          <template #default="scope">
            <!-- <ElInput v-model="scope.row.export_transpor" :placeholder="t('common.inputText')" /> -->
            <ElSelect
              v-model="scope.row.export_transpor"
              @change="select_export_transpor($event, scope.$index)"
              :placeholder="t('common.selectText')"
              filterable
            >
              <ElOption
                v-for="(item, index) in transportArr"
                :key="index"
                :label="item.name"
                :value="item.name"
              />
            </ElSelect>
          </template>
        </ElTableColumn>
        <ElTableColumn prop="transport_text" width="200" label="运输方式" />
        <ElTableColumn prop="send_time" width="200" label="出库日期" />
        <ElTableColumn prop="units" width="200" label="件数" />
        <ElTableColumn prop="weight" width="200" label="重量" />
        <ElTableColumn prop="volume" width="200" label="体积" />
        <ElTableColumn prop="density" width="200" label="密度">
          <template #default="scope">
            {{ Number(scope.row.density).toFixed(2) }}
          </template>
        </ElTableColumn>
        <ElTableColumn prop="export_weight" width="200" label="转出重量">
          <template #default="scope">
            <ElInput v-model="scope.row.export_weight" :placeholder="t('common.inputText')" />
          </template>
        </ElTableColumn>
        <ElTableColumn prop="export_volume" width="200" label="转出体积">
          <template #default="scope">
            <ElInput v-model="scope.row.export_volume" :placeholder="t('common.inputText')" />
          </template>
        </ElTableColumn>
        <ElTableColumn prop="valuePreservationPerKilogram" width="200" label="每公斤货值">
          <template #default="scope">
            {{ (scope.row.usd_value / scope.row.weight).toFixed(2) }}
          </template>
        </ElTableColumn>
        <ElTableColumn prop="usd_value" width="200" label="美金货值" />
        <ElTableColumn prop="export_value" width="200" label="转出货值">
          <template #default="scope">
            <ElInput v-model="scope.row.export_value" :placeholder="t('common.inputText')" />
          </template>
        </ElTableColumn>
        <ElTableColumn prop="export_density" width="200" label="转出密度">
          <template #default="scope">
            <ElInput v-model="scope.row.export_density" :placeholder="t('common.inputText')" />
          </template>
        </ElTableColumn>
        <ElTableColumn prop="quantity" width="200" label="装箱数量" />
        <ElTableColumn prop="transport_type" width="200" label="计算方式">
          <template #default="scope">
            <!-- <ElInput v-model="scope.row.waybill" :placeholder="t('common.inputText')" /> -->
            <ElSelect
              class="qianlan"
              v-model="scope.row.transport_type"
              :placeholder="t('alertEn.PleaseSelectThefreightCalculationMethod')"
              filterable
              @change="yunfeiChange($event, scope.$index)"
            >
              <ElOption
                v-for="item in freightCalculationMethodArr"
                :key="item.key"
                :label="item.label"
                :value="item.value"
              />
            </ElSelect>
          </template>
        </ElTableColumn>
        <ElTableColumn prop="delivery_date" width="200" label="收货日期" />
        <ElTableColumn prop="transport_price" width="200" label="运费价格" />
        <ElTableColumn prop="customs_price" width="200" label="清关价格">
          <template #default="scope">
            <ElInput v-model="scope.row.customs_price" :placeholder="t('common.inputText')" />
          </template>
        </ElTableColumn>
        <ElTableColumn prop="base_freight" width="200" label="业务底价" />
        <ElTableColumn prop="total_fee" width="200" label="总应收费用" />
        <ElTableColumn prop="customs_money" width="200" label="清关金额">
          <template #default="scope">
            <ElInput
              v-model="scope.row.customs_money"
              :disabled="scope.row.transport_type == 1 || scope.row.transport_type == 2"
              :placeholder="t('common.inputText')"
              @blur="sumMoney"
            />
          </template>
        </ElTableColumn>
        <ElTableColumn prop="placeend_text" width="200" label="目的地" />
        <ElTableColumn prop="submarket_text" width="200" label="货物位置" />
        <ElTableColumn prop="client_code" width="200" label="客户号" />
        <ElTableColumn prop="salesman" width="200" label="业务员" />
        <ElTableColumn prop="shouhuo" width="200" label="收货人" />
        <ElTableColumn prop="pack_type_text" width="200" label="付款方式" />
        <ElTableColumn prop="remark2" width="200" label="商标" />
        <ElTableColumn prop="remark" width="200" label="品名备注" />
        <ElTableColumn prop="insurance_rate" width="200" label="客户保率">
          <template #default="scope">
            <ElInput v-model="scope.row.insurance_rate" :placeholder="t('common.inputText')" />
          </template>
        </ElTableColumn>
        <ElTableColumn prop="insurance_rate" width="200" label="保率">
          <template #default="scope">
            <ElInput
              v-model="scope.row.export_insurance_rate"
              :placeholder="t('common.inputText')"
            />
          </template>
        </ElTableColumn>
        <!-- <ElTableColumn prop="" width="200" label="保率百" /> -->
        <ElTableColumn prop="insurance_fee" width="200" label="保险费" />
        <ElTableColumn prop="export_other_fund" width="200" label="其他费用" />
        <ElTableColumn prop="margin" width="200" label="毛利润" />
        <ElTableColumn prop="imitate_text" width="200" label="是否仿牌" />
      </ElTable>
    </ElCol>
  </ElRow>
</template>
<style scoped lang="less">
.upload_file {
  display: inline-block;
  margin-right: 12px;
}

.listForItem {
  display: flex;
  align-items: center;
  margin-bottom: 20px;

  .el-col:nth-of-type(2) {
    font-size: var(--el-form-label-font-size);
    padding: 0 15px;
  }

  .el-col:nth-of-type(1) {
    padding-right: 15px;
  }

  .el-col:nth-of-type(6) {
    padding-left: 15px;
  }

  .el-divider--horizontal {
    margin: 0;
  }

  .el-form-item--default {
    margin-bottom: 0;
  }
}
</style>
